package org.example;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
import org.openqa.selenium.By;

import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

import org.openqa.selenium.support.ui.Select;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;

import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.time.Duration;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
//测试思路
//https://note.youdao.com/web/#/file/recent/note/WEBb5fe9ed643601c6cd1b32dd9f9011b2a/
public class Main {
    static ChromeDriver driver = new ChromeDriver();
    public static int unknown=0;

    public static int sub=0;

    public static int count=0;

    public static int skip=0;
    public static int statusCode;


    public static void main(String[] args) throws NoSuchAlgorithmException, IOException, InterruptedException, KeyManagementException {
        String[] hots=new String[]{"抖音","京东","美团外卖","拼多多","支付宝","快手","饿了么","拍拍贷","小红书","小米","猿辅导","得物","元梦之星","蛋仔派对","天猫","微博","捕鱼"
                ,"携程","淘宝","传奇","小说","叮咚买菜","唯品会","小游戏","同城","战火勋章","这就是江湖","同城"};

        driver.get(" https://p4p.163.com/admin/index?urlToken=e2c93d08cc6e48f19f5dbdeb649251e8");
        driver.manage().window().maximize();

        driver.findElement(By.xpath("/html/body/div[2]/div[1]/div/div/div[1]")).click();

        driver.findElement(By.xpath("/html/body/div[2]/div[1]/div/div/div[2]/div[1]")).click();
        driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(3));

        WebElement ele = driver.findElement(By.cssSelector("#packageName"));
        Select select_ele = new Select(ele);
        select_ele.selectByValue("2023-12");
        driver.findElement(By.xpath("//*[@id=\"startCheck\"]")).click();
        //循环150次
        while (sub<=150) {
            System.out.println("当前查看过 "+ count+ " 条数据");
            System.out.println("跳过 "+ skip+ " 条");
            System.out.println("未知 "+unknown+" 条");
            System.out.println("提交 "+ sub+ " 条");
            //点击落地页url
//        driver.findElement(By.xpath("//*[@id=\"listForm\"]/a")).click();
            //获取落地页url
            String urls = driver.findElement(By.xpath("//*[@id=\"listForm\"]/a")).getText();
            System.out.println(urls);
            //获取链接的状态码
            Thread.sleep(1000);
            statusCode = statusCode(urls);
            System.out.println("Status Code: " + statusCode);
            //如果链接打不开 则直接点击未知 提交
            if (statusCode != 200 && statusCode != 302 && statusCode != 403) {
                unknown();
            } else {
                //此时说明链接能打开 验证热门字段
                //获取标题
                String text = driver.findElement(By.xpath("//*[@id=\"listForm\"]")).getText();
                //此时的text中是全部信息 提取出标题信息
                int index = text.indexOf("标题");
                int end = text.indexOf("一级行业");
                String substring = text.substring(index, end).trim();
                //去除空格
                String title = substring.replace(" ", "");
                System.out.println(title);
                //取出素材url和落地页url
                index = text.indexOf("素材URL");
                end = text.indexOf("落地页URL");
                String materialUrl = text.substring(index, end).trim();
                System.out.println(materialUrl);
                materialUrl=URLPathExample(materialUrl);
                System.out.println("素材URL: " +materialUrl);
                //取出落地页url
                index= text.indexOf("落地页URL");
                end = text.indexOf("提交");
                String landingUrl = text.substring(index, end).trim();
                System.out.println(landingUrl);
                landingUrl=URLPathExample(landingUrl);
                System.out.println("落地页URL: " + landingUrl);
                //查看标题中是否有热门字段
                boolean isHot = false;
                for (String hot : hots) {
                    if (title.contains(hot)) {
                        //存在热门字段 设置二级行业 点击提交 点击下一个
                        isHot=true;
                        productSelect(hot);
                        break;
                    }
                }
                //当不存在热门字段 校验
                if(!isHot) {
                    Thread.sleep(1000);
                    //如果不存在热门字段 取产品多选框中的信息&校验url中是否有该信息的缩写
                    WebElement multiSelectElement = driver.findElement(By.xpath("//*[@id=\"product\"]"));
                    Select select = new Select(multiSelectElement);
                    //获取当前选中的值
                    WebElement firstSelectedOption = select.getFirstSelectedOption();
                    String firstValue = firstSelectedOption.getAttribute("value");
                    System.out.println(firstValue);
                    //如果选中的值为全部 直接点击下一个
                    //如果该值为聚合广告 则直接提交
                    if (firstValue.equals("聚合广告")&&statusCode==200) {
                        submit();
                    }
                    if (firstValue.equals("全部")) {
                        next();
                    } else {
                        //如果选中的值不为全部 取选中的值的信息&校验url中是否有该信息的缩写
                        //将值转换为缩写拼音
                        String s = ChineseToPinyin(firstValue);
                        String s1= toFirstChar(firstValue).toLowerCase();
                        //素材url中是否存在二级行业的缩写或者是小写的首字母
                        boolean material = materialUrl.contains(s)||materialUrl.contains(s1);
                        boolean landing = landingUrl.contains(s)||landingUrl.contains(s1);
                        if (material || landing) {
                            //如果素材url或者落地页url包含二级行业的缩写 点击提交 下一个
                            submit();
                        }
                        //如果不包含 直接下一个
                        next();
                    }
                }
            }
        }

    }

    //提取url中的主机部分
    public static String URLPathExample(String url){
        Pattern pattern = Pattern.compile("(?<=://)[^/?#]+");
        Matcher matcher = pattern.matcher(url);
        if (matcher.find()) {
            return  matcher.group();
        }
        return "";
    }
    public static void productSelect(String str) throws InterruptedException {
        WebElement multiSelectElement = driver.findElement(By.xpath("//*[@id=\"product\"]"));
        Select select = new Select(multiSelectElement);
        boolean optionExists = false;
        //判断二级行业中 是否有该选项
        for (WebElement option : select.getOptions()) {
            if (option.getAttribute("value").equals(str)) {
                optionExists = true;
                break;
            }
        }
        if (optionExists) {
            select.selectByValue(str);
            //选择对应的二级行业  点击提交 下一个
            multiSelectElement.click();
            submit();
        } else {
            //二级行业不存在 直接点击提交 下一个
            submit();
        }
    }
    //将中文字符串转换成拼音首字母
    public static String ChineseToPinyin(String chinese){
        String pinyinStr = "";
        char[] newChar = chinese.toCharArray();
        HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
        defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        for (int i = 0; i < newChar.length; i++) {
            if (newChar[i] > 128) {
                try {
                    pinyinStr += PinyinHelper.toHanyuPinyinStringArray(newChar[i], defaultFormat)[0];
                } catch (BadHanyuPinyinOutputFormatCombination e) {
                    e.printStackTrace();
                }
            }else{
                pinyinStr += newChar[i];
            }
        }
        return pinyinStr;

    }
    //将中文字符串转换成拼音
    public static String toFirstChar(String chinese){
        String pinyinStr = "";
        char[] newChar = chinese.toCharArray();  //转为单个字符
        HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
        defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        for (int i = 0; i < newChar.length; i++) {
            if (newChar[i] > 128) {
                try {
                    pinyinStr += PinyinHelper.toHanyuPinyinStringArray(newChar[i], defaultFormat)[0].charAt(0);
                } catch (BadHanyuPinyinOutputFormatCombination e) {
                    e.printStackTrace();
                }
            }else{
                pinyinStr += newChar[i];
            }
        }
        return pinyinStr;
    }
    //未知
    public static void unknown() throws InterruptedException {
        Thread.sleep(1000);
        //点击未知
        driver.findElement(By.xpath("//*[@id=\"unknownSubmit\"]")).click();
        unknown++;
        count++;
        Thread.sleep(1000);
        //点击下一个
        driver.findElement(By.xpath("//*[@id=\"checkNextSubmit\"]")).click();
        System.out.println("执行了未知");
        Thread.sleep(2000);
    }
    //提交
    public static void submit() throws InterruptedException {
        Thread.sleep(1000);
        //点击提交
        driver.findElement(By.xpath("//*[@id=\"checkSubmit\"]")).click();
        sub++;
        count++;
        Thread.sleep(1500);
        //点击下一个
        driver.findElement(By.xpath("//*[@id=\"checkNextSubmit\"]")).click();
        System.out.println("执行了提交");
        Thread.sleep(1000);
    }
    //下一个
    public static void next() throws InterruptedException {

        Thread.sleep(1000);
        driver.findElement(By.xpath("//*[@id=\"checkNextSubmit\"]")).click();
        System.out.println("执行了下一个");
        skip++;
        count++;
        Thread.sleep(1000);
    }

    public static int statusCode(String urls) throws NoSuchAlgorithmException, KeyManagementException, IOException, InterruptedException {
        Thread.sleep(1000);
        if(!(urls.startsWith("https://") || urls.startsWith("http://"))) return 400;
        try {
            URL url = new URL(urls);
            if(url.getProtocol().equals("http")) {
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                int statusCode = connection.getResponseCode();
                return statusCode;
            } else if(url.getProtocol().equals("https")) {
                SSLContext sslContext = SSLContext.getInstance("SSL");
                sslContext.init(null, new TrustManager[]{new X509TrustManager() {
                    public X509Certificate[] getAcceptedIssuers() {
                        return null;
                    }
                    public void checkClientTrusted(X509Certificate[] certs, String authType) {
                    }
                    public void checkServerTrusted(X509Certificate[] certs, String authType) {
                    }
                }}, new SecureRandom());
                HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
                HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
                connection.setHostnameVerifier((hostname, session) -> true);
                int statusCode = connection.getResponseCode();
                return statusCode;
            } else {
                return 400;
            }
        } catch (MalformedURLException e) {
            return 400;
        }
    }
}
